const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database().collection("user")

exports.main = async (event, context) => {
  let username = event.username
  let password = event.password
  const wxContext = cloud.getWXContext()

  if(username == null)
  {
    const result = await db.where({"openid":wxContext.OPENID}).get()
    if(result.data.length == 0 )
    {
      return {
        code:"404",
        data:{"openid":wxContext.OPENID},
        msg:"username not found",
      }
    }
    return {
      code:200,
      data:{user:result.data[0],"openid":wxContext.OPENID},
      msg:"success"
    }
  }
  else// username found
  {
    const result = await db.where({"sid":username,"password":password}).get()
    if(result.data.length == 0)
    {
      return {
        code:"505",
        data:{"openid":wxContext.OPENID},
        msg:"wrong password",
      }
    }
    else
    {
      let updated = null
      if(result.data[0].openid != wxContext.OPENID)
      {
        const change = await db.where({"sid":username,"password":password}).update({data:{
          openid:wxContext.OPENID
        }})
        updated = change.stats.updated
      }
      else
      {
        updated = 0
      }
      if(updated == 0)
      {
        return {
          code:"500",
          data:{
            user:result.data[0],
            "openid":wxContext.OPENID,
            "updated":updated
          },
          msg:"not change"
        }
      }
      return {
        code:200,
        data:{
          user:result.data[0],
          "openid":wxContext.OPENID,
          "updated":updated
        },
        msg:"success"
      }
    }
    
  }
}